package com.panfeng.xcloud.component.oss;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.panfeng.xcloud.common.core.utils.RandomUtil;
import com.panfeng.xcloud.common.core.utils.StringUtils;
import com.panfeng.xcloud.component.oss.config.AliyunOSSPropConfig;
import com.panfeng.xcloud.component.oss.constants.OSSConstants;
import com.panfeng.xcloud.component.oss.model.UploadResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * 阿里云oss服务
 *
 * @author xiaobo
 * @date 2018-02-07
 */
@Slf4j
@Component
public class OssMaker {

    @Autowired
    private AliyunOSSPropConfig aliyunOSSPropConfig;

    /**
     * 上传文件
     *
     * @param fileName 上传原图片名称
     * @param is 上传文件输入流
     * @return
     */
    public UploadResult uploadFile(String fileName, InputStream is){
        UploadResult uploadResult = new UploadResult();
        log.info(">>> 上传文件fileName：{} <<<",fileName);
        String accessKeyId = aliyunOSSPropConfig.getAccessKeyId();
        String accessKeySecret = aliyunOSSPropConfig.getAccessKeySecret();
        String bucketname = aliyunOSSPropConfig.getBucketname();
        String endpoint = aliyunOSSPropConfig.getEndpoint();
        Integer machineId = aliyunOSSPropConfig.getMachineId();
        //生成保存在服务器的图片名称，延用原后缀名
        String newFileName = OSSConstants.IMG_STORE_URL + RandomUtil.getOrderIdByUUId(machineId) + fileName.substring(fileName.lastIndexOf("."));
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketname, newFileName, is, new ObjectMetadata());
            // 关闭OSSClient。
            ossClient.shutdown();
            //设置结果
            String url = getUrl(newFileName, "");
            uploadResult.setUrl(url);
            log.info(">>> 当前uploadFile上传oss后对应的url为：{} <<<", url);
            uploadResult.setResult(true);
        } catch (Exception e) {
            log.error(">>> 上传oss文件异常：{}",e);
            uploadResult.setUrl("");
            uploadResult.setResult(false);
            e.printStackTrace();
        }
        log.info(">>> 当前uploadFile上传结果为：{} <<<", JSON.toJSONString(uploadResult));
        return uploadResult;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key, String option) {
        String bucketname = aliyunOSSPropConfig.getBucketname();
        String endpoint = aliyunOSSPropConfig.getEndpoint();
        if (StringUtils.isEmpty(key)) {
            return "";
        }
        return "https://" + bucketname + "." + endpoint + "/" + key + option;
    }

}
